/**
 * Created by red on 2017/4/30.
 */
import { parse } from 'utils/';
/**
 * 书籍管理
 * @type {Object}
 */
export default [
  {
    name: '章节章节',
    method: 'list',
    type: 'parse',
    excute: ({ data, fn, errFn } = {}) => {
      parse.query(
        'chapters',
        query => {
          if (!!data.params.book_name) query.contains('book_name', data.params.book_name);
          query.count().then(res => data.page.total = res, err => data.page.total = 0);
          query.skip((data.page.current_page - 1) * data.page.page_size);
          query.limit(data.page.page_size);
        }
      ).filter(x => x.type && x.type === 'result')
        .map(x => {
          return x.result.map(item => ({
            id: item.id,
            book_id: item.get('book_id'),
            book_name: item.get('book_name'),
            title: item.get('title'),
            word_count: item.get('word_count'),
            chapter_index: item.get('chapter_index'),
            gold_coin: item.get('gold_coin'),
          }));
        })
        .subscribe(fn, errFn);
    }
  },
  {
    name: '查询章节',
    method: 'find',
    type: 'parse',
    excute: ({ data, fn, errFn } = {}) => {
      parse.query('chapters', query => query.equalTo('objectId', data))
        .filter(x => x.type && x.type === 'result')
        .map(x => {
          return x.result.map(item => ({
            id: item.id,
            book_id: item.get('book_id'),
            book_name: item.get('book_name'),
            title: item.get('title'),
            word_count: item.get('word_count'),
            chapter_index: item.get('chapter_index'),
            content: item.get('content'),
            gold_coin: item.get('gold_coin'),
          }));
        })
        .subscribe(next => fn(next[0]));
    }
  },
  {
    name: '新增章节',
    method: 'create',
    type: 'parse',
    excute: ({ data, fn, errFn } = {}) => {
      parse.create('chapters', data).subscribe(fn, errFn);
    }
  },
  {
    name: '修改章节',
    method: 'update',
    type: 'parse',
    excute: ({ data, fn, errFn } = {}) => {
      parse.query('chapters', query => query.equalTo('objectId', data.id))
        .filter(x => x.type && x.type === 'result')
        .map(x => x.result[0])
        .subscribe(res => {
          parse.update(res, data).subscribe(fn, errFn);
        });
    }
  },
  {
    name: '删除章节',
    method: 'delete',
    type: 'parse',
    excute: ({ data, fn, errFn } = {}) => {
      parse.delete(data).subscribe(fn, errFn);
    }
  }
];